const {
    pro,
    str_status,
    timeStr
} = require('../common/pro_mysql');
const {
    createToken,
    verifyToken
} = require('../common/jwt_token');

// 登录接口
async function Login(req,res){
    let body = req.body;
	// 拿到前端发送的数据 用户名 密码
    let {loginPhone,loginPassword } = body;
    let sql = `select * from user where loginPhone="${loginPhone}" and loginPassword="${loginPassword}"`
    let data = await pro(sql);
    if(data.code == 1){
        if(data.result.length == 0){
            res.send(str_status(0,'账号或密码错误'))
        }else{
            let data_now = data.result[0];
            delete data_now.loginPassword;
            data_now.token = createToken(data_now);
            res.send(str_status(1,'登录成功',data_now))
            let sql = `update user set lastLoginTime="${Date.now()}" where loginPhone="${loginPhone}"`;
            await pro(sql);
        }
    }else{
        res.send(JSON.stringify(data))
    }
}

// 退出登录接口
async function LoginOut(req,res){
    res.send(str_status(1,'退出成功'))
}

// 注册接口
async function Register(req,res){
    let body = req.body;
    let {loginPhone,loginPassword } = body;
    if(body){
        // console.log(req.session.captcha);
        // if(captcha.toLowerCase() !== req.session.captcha) {
        //     res.send(str_status(0,'验证码输入错误'))
        //     return
        // }
        if(!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(loginPhone)){
            res.send(str_status(0,'请输入正确的手机号'))
            return
        }
        if(loginPassword.length < 6){
            res.send(str_status(0,'密码长度不能小于6位'))
            return
        }
        let sql = `select * from user where loginPhone="${body.loginPhone}"`;
        let {result} = await pro(sql);
        if(result.length >= 1){
            res.send(str_status(0,'用户已存在，请直接登录'))
        }else{
            let sql = `insert into user (loginPhone,loginPassword,createTime) values ("${loginPhone}","${loginPassword}","${Date.now()}")`;
            let data = await pro(sql);
            if(data.code == 0){
                res.send(str_status(data))
            }else{
                res.send(str_status(1,'注册成功,欢迎加入极点商城大家庭'))
            }
        }
    }else{
        res.status(400).send(str_status(0,'参数错误'))
    }
}
// 获取用户信息接口
async function GetUserInfo(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        if(user.code != 0){
            let sql = `select * from user where loginPhone=${user.msg.loginPhone}`;
            let userInfo = await pro(sql);
            if(userInfo.code == 1){
                userInfo = JSON.parse(JSON.stringify(userInfo.result[0]));
                userInfo.token = token;
                let id = userInfo.ID;
                // let sql = `select * from order where user_id=${id}`
                // let {result} = await pro(sql);
                // 待评价
                userInfo.assess = 0;
                // userInfo.assess = result.filter(item => {
                //     return item.status == 3
                // }).length;
                // // 待付款
                userInfo.obligation = 0;
                // userInfo.obligation = result.filter(item => {
                //     return item.status == 0
                // }).length;
                // // 待发货
                userInfo.delivery = 0;
                // userInfo.delivery = result.filter(item => {
                //     return item.status == 1
                // }).length;
                // // 待收货
                userInfo.received = 0;
                // userInfo.received = result.filter(item => {
                //     return item.status == 2
                // }).length;
                delete userInfo.loginPassword
                res.send(str_status(1,'success',userInfo));
            }else{
                res.send(userInfo)
            }
        }else{
            res.send(user);
        }
    }
}
// 修改用户信息接口
async function EditUserInfo (req,res){
    let header = req.rawHeaders;
    let {nickName,sex,desction,headImg} = req.body;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let {msg} =await verifyToken(token);
        let sql = `select * from user where loginPhone="${msg.loginPhone}"`;
        let {result} = await pro(sql);
        if(result.length >= 1){
            let sql = `update user set nickName="${nickName}",sex="${sex}",desction="${desction}",headImg="${headImg}" where ID=${result[0].ID}`;
            let data = await pro(sql);
            res.send(data)
        }else{
            res.send(data)            
        }
    }
}
// 修改密码
async function ForgetPassword(req,res){
    let header = req.rawHeaders;
    let {loginPassword,loginRePassword} = req.body;
    if(loginPassword.length < 6){
        res.send(str_status(0,'新密码长度最低6位'))
        return   
    }
    if(loginPassword != loginRePassword){
        res.send(str_status(0,'两次密码不一致'))
        return   
    }
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let {msg} =await verifyToken(token);
        let {loginPhone} = msg;
        let sql = `select * from user where loginPhone="${loginPhone}"`;
        let {result} = await pro(sql);
        if(result.length >= 1){
            let sql = `update user set loginPassword="${loginPassword}" where ID=${result[0].ID}`;
            let data = await pro(sql);
            res.send(data)
        }else{
            res.send(str_status(0,'错误修改'))            
        }
    }
}
// 投诉/建议
async function Advise(req,res){
    let header = req.rawHeaders;
    let {value,type} = req.body;
    if(value.length < 10){
        res.send(str_status(0,'最短位10位数'))
        return   
    }
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let {msg} =await verifyToken(token);
        let {loginPhone} = msg;
        let sql = `select * from user where loginPhone="${loginPhone}"`;
        let {result} = await pro(sql);
        if(result.length >= 1){
            let sql = `insert into suggest (user_id,type,value,createTime) values (${result[0].ID},${type},"${value}","${Date.now()}")`;
            let data = await pro(sql);
            res.send(data)
        }else{
            res.send(str_status(0,'token过期'))            
        }
    }
}
// 给个Star
async function GiveStar(req,res){
    let {value,point,type} = req.body;
    if(point < 1){
        res.send(str_status(0,'求求了给打个分吧~')) 
        return
    }
    if(point<4 && value == ''){
        res.send(str_status(0,'给我们一点优化建议好嘛，谢谢你呦')) 
        return
    }
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let {msg} =await verifyToken(token);
        let {loginPhone} = msg;
        let sql = `select * from user where loginPhone="${loginPhone}"`;
        let {result} = await pro(sql);
        let result_us = result;
        let polarCount = 0;
        if(type){
            let tSql = `select * from polarTaskList where task_type=4 and task_id in (select ID from polarTaskTime where createTime=${timeStr().s_time} and endTime=${timeStr().e_time})`
            let {result} = await pro(tSql);
            let userArr = JSON.parse(result[0].user_id)
            if(userArr.indexOf(result_us[0].ID) == -1){
                userArr.push(result_us[0].ID)
                let poSql = `insert into polarBean (user_id,count,message,createTime,type) values (${result_us[0].ID},${result[0].task_num},"${result[0].task_title}增加","${Date.now(0)}",1)`
                await pro(poSql);
                let upSql = `update user set polarBean="${(parseInt(result_us[0].polarBean)+result[0].task_num).toFixed(2)}" where ID=${result_us[0].ID}`;
                await pro(upSql);
                let upTaSql = `update polarTaskList set user_id="${JSON.stringify(userArr)}" where ID=${result[0].Id}`
                await pro(upTaSql);
                polarCount += Number(result[0].task_num);
            }else{
                res.send(str_status(0,'已经完成过了',[]))
            }
            return
        }
        if(result_us.length >= 1){
            let sql = `select * from star where user_id="${result_us[0].ID}"`;
            let inSql = `insert into star (user_id,point,message,createTime) values (${result_us[0].ID},${point},"${value || ''}","${Date.now(0)}")`;
            let {result} = await pro(sql);
            if(result.length >= 1){
                let data_now = result[result.length-1].createTim;
                if(Date.now() - data_now > 604800000){
                    let upSql = `update user set polarBean="${(parseInt(result_us[0].polarBean)+polarCount).toFixed(2)}" where ID=${result_us[0].ID}`;
                    let upData = await pro(upSql);
                    let data = await pro(inSql);
                    let poSql = `insert into polarBean (user_id,count,message,createTime,type) values (${result_us[0].ID},15,"Star增加","${Date.now()}",1)`
                    let poData = await pro(poSql);
                    if(upData.code == 1 && data.code == 1 && poData.code == 1){
                        polarCount += 15;
                        res.send(str_status(1,`感谢提交，赠您${polarCount}极豆，7天后可以再来哦`)) 
                    }else{
                        res.status(400).send(str_status(0,'参数错误'))
                    }
                }else{
                    res.send(str_status(0,'距离上次提交还不满7天哦')) 
                }
            }else{
                polarCount += 15;
                let upSql = `update user set polarBean="${(parseInt(result_us[0].polarBean)+polarCount).toFixed(2)}" where ID=${result_us[0].ID}`;
                let upData = await pro(upSql);
                let data = await pro(inSql);
                let poSql = `insert into polarBean (user_id,count,message,createTime,type) values (${result_us[0].ID},15,"Star增加","${Date.now(0)}",1)`
                let poData = await pro(poSql);
                if(upData.code == 1 && data.code == 1 && poData.code == 1){
                    res.send(str_status(1,`感谢提交，赠您${polarCount}极豆，7天后可以再来哦`)) 
                }else{
                    res.status(400).send(str_status(0,'参数错误'))
                }
            }
        }else{
            res.send(str_status(0,'token过期')) 
        }
    }
} 
//获取累计赚取的极豆
async function GetPolar(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let sql = `select SUM(count) from polarBean where user_id=${user.msg.ID} and type=${1}`;
        let {result} = await pro(sql);
        let nSql = `select SUM(count)from polarBean where createTime>=${timeStr().s_time} and createTime<=${timeStr().e_time} and user_id=${user.msg.ID}`
        let nData = await pro(nSql);
        let tSql = `select * from polarTaskList where task_id in (select ID from polarTaskTime where createTime=${timeStr().s_time} and endTime=${timeStr().e_time})`;
        let data = await pro(tSql);
        if(data.code == 1){
            data = data.result;
            let arr = data.filter(item => {
                let userArr = JSON.parse(item.user_id);
                return userArr.indexOf(user.msg.ID) == -1
            })
            res.send(str_status(
                1,
                '获取成功',
                {
                    result: arr,
                    allCount: result[0]['SUM(count)'] || 0,
                    nowCount: nData.result[0]['SUM(count)'] || 0
                }
            ))
        }else{
            res.send(data)
        }
    }
}

// 验证手机号
async function ProvingPhone(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        if(user.code != 0){
            let {code, value} = req.body;
            let sql = `select * from provingCode where Id=${code} and code=${value} and status=0 and user_id=${ID}`;
            let {result} = await pro(sql);
            if(result.length != 0){ 
                // 更新验证码库
                let sql = `update provingCode set status=1 where user_id=${ID}`
                await pro(sql);
                //  查询
                let tSql = `select * from polarTaskList where task_type=2 and task_id in (select ID from polarTaskTime where createTime=${timeStr().s_time} and endTime=${timeStr().e_time})`;
                let {result} = await pro(tSql);
                let userArr = JSON.parse(result[0].user_id)
                if(userArr.indexOf(ID) == -1){
                    // 插入
                    let poSql = `insert into polarBean (user_id,count,message,createTime,type) values (${ID},${result[0].task_num},"${result[0].task_title}增加","${Date.now()}",1)`
                    await pro(poSql);
                    // 查询用户表
                    let uSql = `select * from user where ID=${ID}`;
                    let data = await pro(uSql);
                    // 更新用户表
                    let upSql = `update user set polarBean="${(parseInt(data.result[0].polarBean)+result[0].task_num).toFixed(2)}" where ID=${ID}`;
                    await pro(upSql);
                    userArr.push(ID);
                    // 更新活动表
                    let aSql = `update polarTaskList set user_id="${JSON.stringify(userArr)}" where task_type=2 and task_id=${result[0].task_id}`;
                    await pro(aSql);
                    res.send(str_status(1,'验证成功'))
                }else{
                    res.send(str_status(0,'本轮已经验证过了'))
                }
            }else{
                res.send(str_status(0,'验证码已失效'))
            }
        }else{
            res.send(str_status(0,'token过期'))
        }
    }
}

// 获取极豆明细
async function GetPolarList(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let {page,limit} = req.body;
        let sql = `select * from polarBean where user_id=${ID} order by createTime desc limit ${page*limit || 0},${limit || 10}`
        let data = await pro(sql);
        let date = new Date();
        let sTime = new Date(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} 00:00:00:000`).getTime();
        let uSql = `select SUM(count) from polarBean where user_id=${ID} and createTime>${sTime}`;
        let {result} = await pro(uSql);
        console.log(result);
        let obj = {
            result: data.result,
            nowCount: result[0]['SUM(count)'] || 0
        }
        res.send(str_status(1,'获取成功',obj));
    }
}

// 获取收货地址
async function GetAddressList(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let sql = `select * from address where user_id=${ID} order by is_select desc`;
        let data = await pro(sql);
        res.send(data);
    }
}

// 修改收货地址
async function EditAddress(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let {
            address_id,
            name,
            phone,
            a_desc,
            a_provice,
            a_city,
            a_code,
            is_select
        } = req.body;
        if(
            name.length < 1 ||
            phone.length < 1 ||
            a_desc.length < 1 ||
            a_provice.length < 1 ||
            a_city.length < 1 ||
            a_code.length < 1 ||
            isNaN(Number(is_select)) ||
            !address_id ||
            !ID
            ){
                res.status(400).send(str_status(0,'参数错误',[]))
                return
        }
        // 查询地址是否存在
        let isSql = `select * from address where user_id=${ID} and ID=${address_id}`;
        let data = await pro(isSql);
        if(data.result.length == 0){
            res.send(str_status(0,'此地址不存在',[]))
        }else{
            // 存在的话先判断是否是默认地址
            if(is_select == 1){
                let upSql = `update address set is_select=0 where user_id=${ID}`;
                let upResult = await pro(upSql);
                if(upResult.code == 1){
                    let upIsSql = `update address set is_select=1 where user_id=${ID} and ID=${address_id}`
                    let upIsResult = await pro(upIsSql);
                    if(upIsResult.code == 1){
                        let noSql = `update address set name='${name}',phone='${phone}',a_desc='${a_desc}',a_provice='${a_provice}',a_city='${a_city}',a_code='${a_code}' where user_id=${ID} and ID=${address_id}`
                        let result = await pro(noSql);
                        res.send(result)
                    }else{
                        res.send(upIsResult)
                    }
                }else{
                    res.send(str_status(0,'',upResult.result))
                }
            }else{
                let noSql = `update address set name='${name}',phone='${phone}',a_desc='${a_desc}',a_provice='${a_provice}',a_city='${a_city}',a_code='${a_code}' where user_id=${ID} and ID=${address_id}`
                let result = await pro(noSql);
                res.send(result)
            }
        }
    }
}

// 新增收货地址
async function AddAddress(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let {
            name,
            phone,
            a_desc,
            a_provice,
            a_city,
            a_code,
            is_select
        } = req.body;
        if(
            name.length < 1 ||
            phone.length < 1 ||
            a_desc.length < 1 ||
            a_provice.length < 1 ||
            a_city.length < 1 ||
            a_code.length < 1 ||
            isNaN(Number(is_select))
            ){
                res.send(str_status(0,'参数错误',[]))
                return
        }
        if(is_select == 1){
            let upSql = `update address set is_select=0 where user_id=${ID}`;
            let upResult = await pro(upSql);
            if(upResult.code == 1){
                let sql = `insert into address (user_id,name,phone,a_desc,a_provice,a_city,a_code,is_select,createTime) values (${ID},'${name}','${phone}','${a_desc}','${a_provice}','${a_city}','${a_code}',${is_select},${Date.now()})`;
                let upIsResult = await pro(sql);
                res.send(upIsResult)
            }else{
                res.send(str_status(0,'',upResult.result))
            }
        }else{
            let sql = `insert into address (user_id,name,phone,a_desc,a_provice,a_city,a_code,is_select,createTime) values (${ID},'${name}','${phone}','${a_desc}','${a_provice}','${a_city}','${a_code}',${is_select},${Date.now()})`;
            let upIsResult = await pro(sql);
            res.send(upIsResult)
        }
        
    }
}

// 获取收货地址详情
async function GetAddressDesc(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let {
            address_id
        } = req.body;
        if(!address_id){
            res.status(400).send(str_status(0,'参数错误',[]))
            return
        }
        // 查询地址是否存在
        let isSql = `select * from address where user_id=${ID} and ID=${address_id}`;
        let data = await pro(isSql);
        if(data.result.length == 0){
            res.send(str_status(0,'此地址不存在',[]))
        }else{
            res.send(data)
        }
    }
}

// 删除收货地址
async function DeleteAddressDesc(req,res){
    let header = req.rawHeaders;
    if(header.indexOf('token') == -1 && header.indexOf('Token') == -1){
        res.send(str_status(0,'token过期'))
    }else{
        let index = header.indexOf('token') == -1 ? header.indexOf('Token') : header.indexOf('token');
        let [token] = header.splice(Number(index)+1,1);
        let user =await verifyToken(token);
        let ID = user.msg.ID;
        let {
            address_id
        } = req.body;
        if(!address_id){
            res.status(400).send(str_status(0,'参数错误',[]))
            return
        }
        // 查询地址是否存在
        let isSql = `delete from address where user_id=${ID} and ID=${address_id}`;
        let data = await pro(isSql);
        if(data.result.length == 0){
            res.send(str_status(0,'此地址不存在',[]))
        }else{
            res.send(data)
        }
    }
}

module.exports = {
    Login,
    LoginOut,
    Register,
    GetUserInfo,
    EditUserInfo,
    ForgetPassword,
    Advise,
    GiveStar,
    GetPolar,
    ProvingPhone,
    GetPolarList,
    GetAddressList,
    EditAddress,
    AddAddress,
    GetAddressDesc,
    DeleteAddressDesc
}